package com.lovo.service.impl;

import com.lovo.dao.BaseDAO;
import com.lovo.dao.UserDAO;
import com.lovo.dao.impl.UserDAOImpl;
import com.lovo.pojo.UserDO;
import com.lovo.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();
    @Override
    public UserDO getByUsernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username,pwd);
    }

    @Override
    public void saveMoney(int id, double blance) {
        UserDO user = userDAO.getById(id);
        user.setBlance(user.getBlance() + blance);
        userDAO.update(user);
    }

    @Override
    public void getMoney(int id, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if(user.getBlance() < blance){
            throw new Exception("余额不足");
        }
        user.setBlance(user.getBlance() - blance);
        userDAO.update(user);
    }

    @Override
    public void transfer(int id, String otherAccount, double blance) throws Exception {
        ((BaseDAO)userDAO).setAutoCommit(false);
        UserDO user = userDAO.getById(id);
        UserDO otherUser = userDAO.getByUsername(otherAccount);
        if(otherUser == null){
            ((BaseDAO)userDAO).rollback();
            throw new Exception("账号不存在");
        }
        if(user.getAccount().equals(otherUser.getAccount())){
            ((BaseDAO)userDAO).rollback();
            throw new Exception("不能转给自己");
        }
        if(blance > user.getBlance()){
            ((BaseDAO)userDAO).rollback();
            throw new Exception("余额不足");
        }
        user.setBlance(user.getBlance() - blance);
        otherUser.setBlance(otherUser.getBlance() + blance);
        try{
            userDAO.update(user);
//            int a = 100/0;
            userDAO.update(otherUser);
            ((BaseDAO)userDAO).commit();
        }catch(Exception e){
            ((BaseDAO)userDAO).rollback();
            throw new Exception("数据库出错，转账失败");
        }finally {
            ((BaseDAO)userDAO).close();
        }

    }
}
